import {defineStore} from "pinia";
import {ref} from "vue";
import {
    bindDeviceCidAPI,
    bindWeChatPhoneAPI,
    getOfficialAccountInfoAPI,
    wechatAppletLoginAPI,
    wechatAppLoginAPI,
    wechatH5LoginAPI
} from "../../services/login";
import {conUtils} from "../../utils/conUtils";
import {getBindPidAPI, getUserInfoAPI} from "../../services/me";
import {BaseURL, deviceInfo} from "../../utils/lshttp";
import {receiveAwardAPI} from "../../services/lstz";
import {useCommonInfoStore} from "./commonInfo";
import {getAdCallBackAPI} from "../../services";


export const useUserInfoStore = defineStore("UserInfo", () => {
        const commonInfoStore = useCommonInfoStore() // 使用commonInfoStore状态管理器
        const profile = ref()
        const userInfo = ref()
        const openID = ref()
        const payForm = ref()
        const tuiSong = ref(false)
        const h5WxCodeSave = ref()
        const isOpenWXLogin = ref(false)
        const userId = ref()
        const loginType = ref()
        const isNewUser = ref(true)

        const setIsOpenWXLogin = (val) => {
            isOpenWXLogin.value = val
        }
        const setTuiSong = (val) => {
            tuiSong.value = val
        }
        const setPayForm = (val) => {
            payForm.value = val
        }
        const setUserId = (val) => {
            userId.value = val
        }
        const setOpenID = (val) => {
            openID.value = val
        }
        const clearOpenID = () => {
            openID.value = ''
        }
        // 保存会员信息，登录时使用
        const setProfile = (val) => {
            profile.value = val
        }
        const setLoginType = (val) => {
            loginType.value = val
        }
        // 保存用户信息，登录时使用
        const setUserInfo = (val) => {
            userInfo.value = val
        }
        // 是否是新用户
        const setIsNewUser = (val) => {
            isNewUser.value = val.create_order_num + val.mt_create_order_num === 0;
        }
        // 清理会员信息，退出时使用
        const clearProfile = async () => {
            profile.value = undefined
            userInfo.value = undefined
            await uni.navigateBack()
        }

        const getUserInfo = async () => {
            // 获取用户信息
            const res = await getUserInfoAPI()
            console.log('获取用户信息===',res.result)
            setUserInfo(res.result)
            setIsNewUser(res.result)
            // userInfo.value.amount = userInfo.value.amount - money
            conUtils('用户信息', userInfo.value)
            conUtils('amount', userInfo.value.amount)
        }
        const platform = uni.getSystemInfoSync().platform;
        const isLogin = (content = '您还未登录，是否去登录？', loginType = 0) => {
            // conUtils('isLogin', profile.value?.token)
            if (profile.value?.token) {
                conUtils('isLogin', true)
                return true
            }
            conUtils('isLogin', false)
            uni.showModal({
                title: '温馨提示',
                content,
                success(res) {
                    if (res.confirm) {
                        // #ifdef APP-PLUS
                        if (!isOpenWXLogin.value) {
                            uni.navigateTo({
                                url: '/pages/login/phone_login'
                            })
                            return false
                        }
                        // #endif
                        // #ifdef H5
                        // H5存储登录类型
                        setLoginType(loginType)
                        // #endif
                        uni.navigateTo({
                            url: '/pages/login/login'
                        })
                        return false
                    }
                }
            })
            return false
        }
        const toLogin = () => {
            if (profile.value?.token) {
                conUtils('isLogin', true)
                return true
            }
            conUtils('isLogin', false)
            uni.navigateTo({
                url: '/pages/login/login'
            })
            return false
        }
        const isLoginBool = () => {
            // conUtils('isLogin', profile.value?.token)
            if (profile.value?.token) {
                conUtils('isLogin', true)
                return true
            }
            conUtils('isLogin', false)
            return false
        }
        // 获取用户openid
        const getUserOpenID = () => {
            uni.showLoading({
                title: '正在授权',
                mask: true,
            })
            uni.getUserProfile({
                desc: '支付',
                success: (res) => {
                    conUtils('用户信息', res)
                    uni.login({
                        provider: 'weixin',
                        success: async function (login_res) {
                            // const res = await getUserOpenIdAPI(login_res.code)
                            // console.log('getUserOpenIdAPI', res)
                            // profile.value.info = res.result.info
                            // await uni.showToast({
                            //     title: '授权成功',
                            //     icon: 'none',
                            //     duration: 1500,
                            //     mask: true,
                            // })
                        },
                    })
                },
                fail: (res) => {
                    uni.hideLoading()
                    conUtils(res)
                    uni.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1500,
                        mask: true,
                    })
                },
                // complete: () => {
                //   uni.hideLoading()
                // },
            })
        }
        // 登录添加访问记录
        const device_info = {
            device_id: deviceInfo.deviceId,
            platform_type: deviceInfo.platform,
            uniPlatform_type: deviceInfo.uniPlatform,
            deviceBrand: deviceInfo.deviceBrand,
            safeArea: deviceInfo.safeArea,
        }
        // 微信登录
        const authLogin = async (type = 0, h5WxCode = '') => {
            // #ifdef H5
            if (h5WxCode === null || h5WxCode === '' || h5WxCode === h5WxCodeSave.value) {
                const res = await getOfficialAccountInfoAPI()
                let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + res.result.appid + '&redirect_uri=' +
                    encodeURIComponent(BaseURL + '/index.html#/pages/login/login') + '&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect';
                window.location.replace(url);
                return
            }
            h5WxCodeSave.value = h5WxCode
            const res = await wechatH5LoginAPI(h5WxCode, device_info, commonInfoStore.invite_link_id)
            await setInfo(res, type)
            // #endif
            // #ifdef APP-PLUS
            uni.login({
                "provider": "weixin",
                "onlyAuthorize": true, // 微信登录仅请求授权认证
                success: async function (loginRes) {
                    const res = await wechatAppLoginAPI(loginRes.code, device_info, commonInfoStore.invite_link_id)
                    await setInfo(res, type)
                },
                fail: (err) => {
                    uni.showToast({
                        title: '登录失败',
                        icon: 'none',
                        duration: 1500,
                        mask: true,
                    })
                    conUtils(err)
                }
            })
            // #endif
            // #ifdef MP-WEIXIN
            uni.showLoading({
                title: '正在登录',
                mask: true,
            })
            uni.getUserProfile({
                desc: '登录',
                success: (userInfos) => {
                    // conUtils('用户信息', userInfos)
                    uni.login({
                        provider: 'weixin',
                        success: async function (login_res) {
                            uni.hideLoading()
                            // conUtils("getUserProfile", userInfos)
                            // conUtils("login", login_res)
                            console.log('用户微信信息=',login_res)
                            const res = await wechatAppletLoginAPI(login_res.code, userInfos.userInfo.avatarUrl, userInfos.userInfo.nickName, device_info, commonInfoStore.invite_link_id)

                            // 微信授权手机号登录
                            /* if (e){
                                console.log('用户信息==',e.detail)
                                await bindWeChatPhoneAPI(e.detail.code)
                            } */
                            // conUtils('res.result.token', res.result.token)

                            await setInfo(res, type)
                        },
                    })
                },
                fail: (res) => {
                    uni.hideLoading()
                    uni.showToast({
                        title: '登录失败',
                        icon: 'none',
                        duration: 1500,
                        mask: true,
                    })
                    conUtils(res)
                },
            })

            // #endif
        }
        const setInfo = async (res, type) => {
            conUtils('setProfile', res.result)
            // 保存会员信息
            setProfile(res.result)
            // 保存设备信息cid
            await bindDeviceCidAPI(uni.getStorageSync('cid'))
            // 保存上级ID接口和渠道来源
            if (commonInfoStore.parentId) {
                await getBindPidAPI(commonInfoStore.parentId, commonInfoStore.source)
            }
            // 广告平台返回值callback提交到后台
            if (commonInfoStore.callback){
                await getAdCallBackAPI({
                    callback: commonInfoStore.callback,
                    eventType: 'login'
                })
            }
            await uni.showToast({
                title: res.msg,
                icon: 'none',
                duration: 1500,
                mask: true,
            })
            if (type === 1) {
                return
            }
            const resUser = await getUserInfoAPI()
            console.log('微信登录结果=',resUser)
            setUserInfo(resUser.result)
            conUtils('setUserInfo', resUser.result)
            setTimeout(async () => {
                // 判断登录后是否是新用户，从而判断首页新用户指引弹窗
                console.log('是否是新用户',isNewUser.value)
                let userInfo = resUser.result
                if (userInfo.create_order_num + userInfo.mt_create_order_num === 0){
                    commonInfoStore.getShowExecuteEvent(true)
                    setIsNewUser(userInfo)
                }else {
                    commonInfoStore.getShowExecuteEvent(false)
                    setIsNewUser(userInfo)
                }
                conUtils('LoginBack')
                // #ifdef MP-WEIXIN || APP-PLUS
                uni.$emit('isSuccess', true)
                await uni.navigateBack()
                // #endif
                // #ifdef H5
                if (loginType.value === 1) {
                    await uni.navigateTo({url: '/pages_gold/mt_redbag'})
                } else {
                    await uni.switchTab({url: '/pages/me/me'})
                }
                // #endif
                // if (!resUser.result.username) {
                //   await uni.navigateTo({
                //     url: "/pages/me/settinginfo"
                //   })
                // }
            }, 1000)
        }

        // 记得 return
        return {
            profile,
            userInfo,
            openID,
            payForm,
            tuiSong,
            isOpenWXLogin,
            h5WxCodeSave,
            userId,
            loginType,
            isNewUser, // 是否新用户
            setIsOpenWXLogin,
            setTuiSong,
            getUserInfo,
            setOpenID,
            clearOpenID,
            setProfile,
            setUserInfo,
            clearProfile,
            toLogin,
            authLogin,
            getUserOpenID,
            isLogin,
            isLoginBool,
            setPayForm,
            setUserId,
            setLoginType,
        }
    },
    {
        // 配置持久化
        persist: {
            // 调整为兼容多端的API
            storage: {
                setItem(key, value) {
                    uni.setStorageSync(key, value)
                },
                getItem(key) {
                    return uni.getStorageSync(key)
                },
            },
        },
    },
)
